package logic

import (
	"context"
	"fmt"
	"store/cache"
	"store/models"
	"store/pkg"
	"store/storerpc/internal/svc"
	"store/storerpc/storerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *storerpc.LoginRequest) (*storerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		user = models.User{
			Account:  in.Account,
			Password: pkg.Md5(in.Password),
			Info:     "",
			Image:    "https://ts1.tc.mm.bing.net/th/id/OIP-C.p6hdmBEvZCMwVcWDVnQr0QAAAA?w=205&h=211&c=8&rs=1&qlt=90&o=6&cb=12&dpr=1.3&pid=3.1&rm=2",
		}
		models.DB.Debug().Create(&user)
	} else {
		if user.Password != pkg.Md5(in.Password) {
			return nil, fmt.Errorf("密码错误,登录失败")
		}
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	return &storerpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
